import { createRenderer } from '../runtime-core/render'
import { isOn } from '../shared/index'

function createElement(type) {
    return document.createElement(type);
}
function patchProp(el, key, prevVal, nextVal) {
    // 处理 props 中的数组 value ，用空格拼接
    if (Array.isArray(nextVal)) {
        nextVal = nextVal.reduce((prev, next) => { return prev + " " + next }, '').trim();
    }

    if (isOn(key)) {
        const event = key.slice(2).toLocaleLowerCase();
        el.addEventListener(event, nextVal);
    }

    // 情况2： props 的值设置为 null 或者 undefined 
    if (nextVal === null || nextVal === undefined) {
        el.removeAttribute(key);
        return;
    }
    el.setAttribute(key, nextVal);

}

function insert(el, parent) {
    parent.append(el);
}

function remove(child) {
    let parent = child.parentNode;
    if (parent) {
        parent.removeChild(child);
    }
}

function setElementText(el, text) {
    el.textContent = text;
}

const renderer = createRenderer({ createElement, patchProp, insert, remove, setElementText })



export function createApp(...args) {
    return renderer.createApp(args[0]);
}